var webim = require('../../../../utils/webim.js');
var webimhandler = require('../../../../utils/webim_handler.js');
var tls = require('../../../../utils/tls.js');
var Config = {
  sdkappid: 1400068801,
  accountType: 22679,
  accountMode: 1, //帐号模式，0-表示独立模式，1-表示托管模式
  avChatRoomId: '@TGS#aVRUL5BFW'
};
tls.init({
  sdkappid: Config.sdkappid
});
var app = getApp();
var pusher;
var scope = false;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    info: null,
    is_push: false,
    flow_list: [],
    is_first:true
  },
  backto: function (e) {
    wx.navigateBack({})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var t = this
    console.log(t.data)
    console.log('onload')
    if(!t.data.id){
      this.setData({
        id: options.id
      })
    }
    t.aa()
    if(!scope){
      t.authorize();
    }
  },
  authorize:function(){
    var t = this
    wx.getSetting({
      success: (res) => {
        var scope = res.authSetting;
        //判断是否授权
        if (!scope['scope.camera'] || !scope['scope.record']) {
          wx.authorize({
            scope: 'scope.camera',
            success: function (e) {
              if (!scope['scope.record']) {
                wx.authorize({
                  scope: 'scope.record',
                  success: function () {
                    //授权成功，调用下一步
                    t.setData({
                      scope:true
                    })
                  }, fail: function (e) {
                    console.log(e)
                    wx.showModal({
                      title: '提示',
                      content: '请授权1',
                      success: function (r) {
                        if (r.confirm) {
                          t.setData({
                            scope: false
                          })
                          t.authorize()
                        }
                      }
                    })
                  }
                })
              }
              else {
                t.setData({
                  scope: true
                })
              }
            }, fail: function (e) {
              console.log(e)
              wx.showModal({
                title: '提示',
                content: '请授权2',
                success: function (r) {
                  if (r.confirm) {
                    t.setData({
                      scope: false
                    })
                    t.authorize()
                  }
                }
              })
            }
          })
        } else {
          //都授权
          t.setData({
            scope: true
          })
        }
      }
    })
  },
  aa:function(){
    wx.showLoading({
      title: '加载中…',
    })
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    var self = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo1(function (userInfo) {
      //更新数据
      self.setData({
        userInfo: userInfo
      })
      self.login(function () {
        self.initIM(userInfo);
      });
    })
    app.ihttpGet("https://www.58zltc.com/api.php/Zhibo/getRtmp/id/" + this.data.id, res => {
      console.log(res);
      this.setData({
        info: res.data
      })
    })
    pusher = wx.createLivePusherContext('pusher');
  },
  start_push: function (e) {
    var t =this
    var is_first = t.data.is_first
    if (scope) {
      t.authorize();
    }
    console.log(is_first)
    if (!is_first) {
      pusher.resume({
        success: e => {
          console.log('resume-success')
          console.log(e)
          t.setData({
            is_push: true,
            scope: false
          })
        }
      });
    } else {
      pusher.start({
        success: function(e) {
          console.log('start-success')
          t.setData({
            is_push: true,
            scope: false,
            is_first:false
          })
          console.log(t.data)
        },
        fail: function (e){
          console.log('start-f')
          console.log(e)
        }
      });
    }
  },
  end_push: function () {
    var t =this
    if (scope) {
      t.authorize();
    }
    pusher.pause({
      success: e => {
        t.setData({
          is_push: false,
          scope: false,
          is_first: false
        })
      }
    });
  },
  statechange: function (e) {
    // if (scope) {
    //   t.authorize();
    // }
    // wx.showToast({
    //   icon: 'none',
    //   title: "'" + e.detail.code+ "'",
    // })
  },
  qie: function (e) {
    var t =this
    pusher.switchCamera({
      success: e => {
        t.setdata({
          scope: false
        })
        console.log(e);
      }
    });
  },
  login: function (cb) {
    var self = this;
    tls.anologin(function (data) {
      console.log(data);
      self.setData({
        Identifier: data.Identifier,
        UserSig: data.UserSig
      })
      cb();
    });
  },
  receiveMsgs: function (data) {
    if (!data.content) {
      return;
    }
    var msg = restHTML(data.content);
    try {
      msg = JSON.parse(msg);
    } catch (e) {
      msg = msg;
    }
    msg = typeof (msg) == "object" ? msg.msg : msg;
    if (!msg) {
      return;
    }
    var flow_list = this.data.flow_list;
    if (data.fromAccountNick == '@TIM#SYSTEM') {
      if (data.content.indexOf(this.data.Identifier) >= 0) {
        webimhandler.onSendMsg("加入了房间", function () { });
      }
    } else {
      flow_list.push({ nickname: data.fromAccountNick, content: data.content, type: 'reply' });
      this.setData({
        flow_list: flow_list
      });
    }
    console.log(flow_list);
  },
  initIM: function (userInfo) {
    var self = this;
    // Config.avChatRoomId = self.data.id;
    webimhandler.init({
      accountMode: Config.accountMode,
      accountType: Config.accountType,
      sdkAppID: Config.sdkappid,
      avChatRoomId: Config.avChatRoomId,
      selType: webim.SESSION_TYPE.GROUP,
      selToID: Config.avChatRoomId,
      selSess: null //当前聊天会话
    });
    //当前用户身份
    var loginInfo = {
      'sdkAppID': Config.sdkappid, //用户所属应用id,必填
      'appIDAt3rd': Config.sdkappid, //用户所属应用id，必填
      'accountType': Config.accountType, //用户所属应用帐号类型，必填
      'identifier': self.data.Identifier, //当前用户ID,必须是否字符串类型，选填
      'identifierNick': userInfo.nickName, //当前用户昵称，选填
      'userSig': self.data.UserSig, //当前用户身份凭证，必须是字符串类型，选填
    };
    //监听（多终端同步）群系统消息方法，方法都定义在demo_group_notice.js文件中
    var onGroupSystemNotifys = {
      "5": webimhandler.onDestoryGroupNotify, //群被解散(全员接收)
      "11": webimhandler.onRevokeGroupNotify, //群已被回收(全员接收)
      "255": webimhandler.onCustomGroupNotify //用户自定义通知(默认全员接收)
    };
    //监听连接状态回调变化事件
    var onConnNotify = function (resp) {
      switch (resp.ErrorCode) {
        case webim.CONNECTION_STATUS.ON:
          //webim.Log.warn('连接状态正常...');
          break;
        case webim.CONNECTION_STATUS.OFF:
          webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
          break;
        default:
          webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
          break;
      }
    };
    //监听事件
    var listeners = {
      "onConnNotify": webimhandler.onConnNotify, //选填
      "onBigGroupMsgNotify": function (msg) {
        webimhandler.onBigGroupMsgNotify(msg, function (msgs) {
          self.receiveMsgs(msgs);
        })
      }, //监听新消息(大群)事件，必填
      "onMsgNotify": webimhandler.onMsgNotify, //监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
      "onGroupSystemNotifys": webimhandler.onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，必填
      "onGroupInfoChangeNotify": webimhandler.onGroupInfoChangeNotify //监听群资料变化事件，选填
    };

    //其他对象，选填
    var options = {
      'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
      'isLogOn': false //是否开启控制台打印日志,默认开启，选填
    };

    if (Config.accountMode == 1) { //托管模式
      webimhandler.sdkLogin(loginInfo, listeners, options, Config.avChatRoomId);
    } else { //独立模式
      //sdk登录
      webimhandler.sdkLogin(loginInfo, listeners, options);
    }
  },
})
function restHTML(str) {
  if (typeof str != 'string') {
    return '' + str;
  }
  return str.replace(/&(lt|gt|amp|quot|#0?34|apos|#0?39);/g, function ($0, $1) {
    switch ($1) {
      case 'lt':
        return '<';
      case 'gt':
        return '>';
      case 'amp':
        return '&';
      case 'quot':
      case '#34':
      case '#034':
        return '"';
      case 'apos':
      case '#39':
      case '#039':
        return '\'';
    }
  });
}